class PickupController < ApplicationController
  before_filter :correct_bili_name?, :except => :index
  layout "need_bili_name"
  def index
    if current_bili_user
      redirect_to :action => :new
    else
      render :layout => "application"
    end
  end

  def new
    @pickup = Pickup.new
  end

  def create
    params[:pickup][:avid].delete! 'av'
    @pickup = Pickup.new params[:pickup]
    @pickup.uname = current_bili_user
    work = @pickup.work
    @pickup.ptype = @pickup.check_type(work)
    @pickup.wname = (work.name rescue "[未知投稿名称]")
	@pickup.status = -1
    if @pickup.save
      require 'open-uri'
      uri = URI.parse(session[:user_face_url])
      begin
        uri.open { |f|
          f2 = File.new("#{Rails.public_path}/images/face/#{@pickup.id}", "wb") #Binary mode
          f2.write f.read
          f2.close
        }
      rescue
      end
      flash[:notice] = @pickup
      redirect_to :action => :confirm
    else
      render :action => :new
    end
  end
  
  def confirm
    redirect_to :action => :index unless flash[:notice]
  end
  
  def s
    pickup = Pickup.find_by_id params[:id]
	if pickup && pickup.uname == current_bili_user && pickup.status < 0
	  pickup.update_attribute :status, 0
	  flash[:notice] = pickup.ptype
	  redirect_to :action => :succ
	else
	  redirect_to :action => :index
	end
  end
  
  def succ
    if flash[:notice]
       @mes = (case flash[:notice]
         when 1
            "您所提交的推荐人气较高，在以往的周刊中有不错的名次，可能无法在推荐部分中使用"
         when 2
            "您可能是在推荐自己的投稿，在周刊中使用自推荐要求相对较高，且会在周刊中注明是自推荐"
         when 3
            "您所提交的推荐理由偏长，可能无法在推荐部分中使用"
         when 4
            "您所提交的推荐是近期的新投稿，被采用的优先级可能会比旧投稿低"
       end)
    else
       redirect_to :controller => :index, :action => :logout
    end
  end

end
